package leetcode;

import java.util.Arrays;

/**
 * 合并区间
 */
public class LeetCode56 {
    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) return intervals;
        // 按照起点排序
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
        int [] prev = intervals[0];
        int count = 1;
        for (int i = 1; i < intervals.length; i++) {
            int [] cur = intervals[i];
            if (prev[1] >= cur[0] && prev[1] >= cur[1]) {
                intervals[i] = null;
            } else if (prev[1] >= cur[0]) {
                prev[1] = cur[1];
                intervals[i] = null;
            } else {
                count++;
                prev = cur;
            }
        }
        int [][] result = new int[count][];
        int index = 0;
        for (int i = 0; i < intervals.length; i++) {
            if (intervals[i] != null) result[index++] = intervals[i];
        }
        return result;
    }
}